<template>
	<view class="restaurant-edit-dish-container">
		<common-title :title="titleContent" @clickLeft="backToUpPage"></common-title>
		<view class="restaurant-edit-dish-form">
			<uni-forms ref="editDishesForm" :modelValue="dishInfo" :rules="editDishesFromRules">
				<!-- 菜名：dishName -->
				<uni-forms-item label="菜名" required name="dishName">
					<uni-easyinput @blur="removeSpaces('dishName')" v-model="dishInfo.dishName" placeholder="请输入菜名"></uni-easyinput>
				</uni-forms-item>
				<!-- 定价：price -->
				<uni-forms-item label="定价" required name="price">
					<uni-easyinput @blur="removeSpaces('price')" v-model="dishInfo.price" placeholder="请输入定价"></uni-easyinput>
				</uni-forms-item>
				<!-- 菜品图片：dishImage -->
				<uni-forms-item label="菜品图片" required name="dishImage">
					<uni-file-picker :limit="1" file-mediatype="image" 
									 :sizeType="['compressed']" @select="imageUploadSelect" 
									 @delete="imageUploadDelete"
									 title="(画幅4:3)"
									 :auto-upload="true" disable-preview 
									 :value="dishImgeFile"/>
				</uni-forms-item>
				<!-- 描述：description -->
				<uni-forms-item label="菜品描述" name="description">
					<uni-easyinput @blur="removeSpaces('description')" type="textarea" v-model="dishInfo.description" placeholder="请输入菜品描述(30字以内)"/>
				</uni-forms-item>
				<!-- 是否上架：status -->
				<uni-forms-item label="状态" name="staus" required>
					<uni-data-checkbox v-model="dishInfo.status" :localdata="dishesStatus"></uni-data-checkbox>
				</uni-forms-item>
				
				<!-- 菜品类别：categoryId -->
				<uni-forms-item label="菜品类别" name="categoryId" required>
					<uni-data-select
					      v-model="dishInfo.categoryId"
					      :localdata="categoryId"
					/>
				</uni-forms-item>
			</uni-forms>
		</view>
		
		<!-- 底部操纵按钮 -->
		<view class="buttonOption">
		    <view 
		        class="editDishButton" 
		        @click="submit" 
		        :class="{'active': isPressedEdit}" 
		        @touchstart="onPressEdit" 
		        @touchend="onReleaseEdit">
		        修改菜品
		    </view>
		</view>
	</view>
</template>

<script setup>
	
	import { ref, onMounted } from "vue";
	import { useRoute } from "vue-router"; // 使用 vue-router 来获取路由参数
	import { apiGetRestaurantDishById, apiGetRestaurantAllCategories, apiPutRestaurantDish } from "@/utils/apiRestaurant.js";
	import { apiUploadFile } from '@/utils/apiFiles.js';
	
	//================================common-title=========================================
	//标题内容
	const titleContent = ref({
		left:'返回',
		midst:'餐厅-修改菜品'
	});
	
	//返回
	const backToUpPage = () => {
		if (fromPage.value === 'available') {
			uni.redirectTo({
				url:'/pages/manage/restaurant_manage/restaurant-available-dishes'
			})
		} else if(fromPage.value === 'removed') {
			uni.redirectTo({
				url:'/pages/manage/restaurant_manage/restaurant-removed-dishes'
			})
		}
	};
	
	//================================uni-form=========================================
	
	//获取数据，根据id查询菜品信息
	//先获取id
	//定义承接菜品信息的变量
	// 定义初始状态
	const initialFormData = {
	    dishName: '',
	    price: '',
	    dishImage: null,
	    description: '',
		status: null,
	    categoryId: null
	};
	
	// 创建 承接菜品信息的变量 对象
	const dishInfo = ref({ ...initialFormData });
	// 创建 承接菜品信息的变量 对象，用来存储老数据
	const dishInfoOld = ref({ ...initialFormData });
	// 创建表单引用对象
	const editDishesForm = ref(null);
	// 创建表单规则
	// 表单验证规则
	const editDishesFromRules = {
		dishName: {
			rules: [
				{
					required: true,
					errorMessage: '菜名不能为空'
				},
				{
					minLength: 1,
					maxLength: 10,
					errorMessage: '菜名长度在 {minLength} 到 {maxLength} 个字符',
					validateFunction(rule, value, data, callback) {
						// 正则表达式定义为字符串
						const pricePattern = new RegExp('^(?=[^_])[\\u4e00-\\u9fa5A-Za-z0-9_]+$');
						
						if (!pricePattern.test(value)) {
							callback('只能是中文，字母，数字，下划线，且不能下划线开头');
						} else {
							callback(); // 校验通过
						}
					}
				}
			]
		},
		price: {
			rules: [
				{
					required: true,
					errorMessage: '价格不能为空'
				},
				{
					validateFunction(rule, value, data, callback) {
						// 正则表达式定义为字符串
						const pricePattern = new RegExp('^(0|[1-9]\\d*)(\\.\\d{1,2})?$');
			
						if (!pricePattern.test(value)) {
							callback('价格格式不正确，最多为两个小数位的金额');
						} else {
							callback(); // 校验通过
						}
					}
				}
			]
		},
		dishImage: {
			rules: [
				{
					required: true,
					errorMessage: '图片不能为空'
				}
			]
		},
		description: {
			rules: [
				{
					minLength: 0,
					maxLength: 30,
					errorMessage: '描述长度在 {minLength} 到 {maxLength} 个字符',
				}
			]
		},
		status: {
			rules: [
				{
					required: true,
					errorMessage: '菜品状态不能为空'
				}
			]
		},
		categoryId: {
			rules: [
				{
					required: true,
					errorMessage: '请选择类别'
				}
			]
		}
	}
	//菜品状态
	const dishesStatus = ref([
		{text: '上架',value: 1}, 
		{text: '下架',value: 0}
	]);
	
	//TODO:菜品类别
	
	const categoryId = ref([]);
	
	const getAllCategories = async () => {
		try{
			let res = await apiGetRestaurantAllCategories();
			categoryId.value = res.map(item => ({
				text: item.categoryName,
				value: item.id
			}));
		}catch(e){
			//TODO handle the exception
		}
	};
	getAllCategories();
	
	let changeImage = ref(false);
	//选择图片成功执行的方法
	const imageUploadSelect = (e) => {
		dishInfo.value.dishImage = e.tempFilePaths[0];
		changeImage.value = true;
	};
	
	//移除图片
	const imageUploadDelete = (e) => {
		dishInfo.value.dishImage='';
	};
	
	// 根据字段名移除前后空格的通用方法
	const removeSpaces = async (field) => {
		
		if (field in dishInfo.value) {
			// trim 之后的结果
			const trimmedValue = dishInfo.value[field].trim();
			// 更新值
			dishInfo.value[field] = trimmedValue;
		}
	};
	
	const dishImgeFile = ref({ url: '', name: '', extends: '' }); // 初始化 dishImgeFile 为一个对象
	
	const fromPage = ref(null);
	
	// onMounted 生命周期钩子，获取菜品信息
	onMounted(async () => {
	    const route = useRoute(); // 获取路由实例
	    const dishId = route.query.id; // 从路由查询参数中获取 id
		const from = route.query.from;
		// console.log(from);
		fromPage.value = from;
		editDishesForm.value.setRules(editDishesFromRules);
	
	    // 调用 API 获取菜品信息
	    try {
	        const response = await apiGetRestaurantDishById(dishId);
			// 将 price 变成字符串
			response.price = String(response.price);
	        dishInfo.value = response; // 假设 API 返回的数据在 response.data 中
			dishInfoOld.value = JSON.parse(JSON.stringify(response));
			// 确保在 API 响应后更新 dishImgeFile
			dishImgeFile.value = {
				url: dishInfo.value.dishImage || '', // 使用默认值避免 null
				name: '111.jpg', // 可根据需要修改
				extends: 'jpg' // 可根据需要修改
			};
	    } catch (error) {
	        console.error('Failed to fetch dish info:', error);
	    }
	});
	
	//=======================底部按钮=======================================
	
	const isPressedEdit = ref(false);
	//点击新增按钮
	const onPressEdit = () => {
		isPressedEdit.value = true;
	};
	
	//长按新增按钮
	const onReleaseEdit = () => {
		isPressedEdit.value = false;
	};
	
	// 提交修改
	let isSubmitting = false; // 标志变量，初始化为 false
	const submit = async () => {
		if (isSubmitting) return; // 如果正在提交，则直接返回
			
		isSubmitting = true; // 设置为正在提交状态
		
		let isEqual = JSON.stringify(dishInfo.value) === JSON.stringify(dishInfoOld.value);
		if (isEqual) {
			uni.showToast({
				title:"无改动",
				icon:'none'
			});
			isSubmitting = false; // 重置提交状态
		}else {
			try {
			    // 等待表单验证的结果
			    await editDishesForm.value.validate();
				
				// 创建 FormData 实例
				const formData = new FormData();
				let dishImageName = null;
				// 上传图片并获取返回的文件名
				if (changeImage.value) {
					dishImageName = await apiUploadFile(dishInfo.value.dishImage);
				}
				// 将表单数据添加到 FormData
				for (const key in dishInfo.value) {
					formData.append(key, dishInfo.value[key]);
				}
				
				// 将上传的图片名称加入到 FormData 中
				formData.set('dishImage', dishImageName);

				
				// 用户确认修改
				const res = await uni.showModal({
					title: '提示',
					content: '是否确认修改？'
				});
				if (res.confirm) { // 检查用户是否点击了“确认”
					const response = await apiPutRestaurantDish(formData); // 等待 API 返回
						
					if (response === '200') { // 假设 response 包含 status 属性
						uni.showToast({
							title: "修改菜品成功",
							icon: 'success'
						});
						if (fromPage.value === 'available') {
							uni.redirectTo({
								url:'/pages/manage/restaurant_manage/restaurant-available-dishes'
							})
						} else if(fromPage.value === 'removed') {
							uni.redirectTo({
								url:'/pages/manage/restaurant_manage/restaurant-removed-dishes'
							})
						}
					} else {
						uni.showToast({
							title: "修改失败，请稍后再试",
							icon: 'none'
						});
					}
				}
				
			    
				
			} catch (err) {
			    console.log('表单错误信息：', err); // 捕获验证和 API 调用中的错误
			} finally {
				// TODO: 提交后清除表单信息等操作
			    
				isSubmitting = false; // 重置提交状态
				
				
			}
		}
	};

	
	
</script>

<style lang="scss" scoped>
	.restaurant-edit-dish-container{
		.restaurant-edit-dish-form{
			padding:30rpx;
		}
		.buttonOption{
			position: absolute;
			width: 670rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			bottom: 50rpx;
			
			font-weight: bold;
			font-size: 36rpx;
			color: #000000 ;
			padding: 30rpx;
			.editDishButton{
				width: 400rpx;
				height: 120rpx;
				border-radius: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: $brand-theme-color;
				box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);
			}
			.editDishButton.active {
			    background-color: #e4e4e4; /* 按下时的背景色 */
			    color: #999; /* 按下时的文字颜色 */
			}
		}
	}
</style>